package com.ls.lserp.modules.custom.web;
import freemarker.template.Configuration;
import com.ls.lserp.common.beanvalidator.BeanValidators;
import com.ls.lserp.common.config.Global;
import com.ls.lserp.common.persistence.AjaxDone;
import com.ls.lserp.common.persistence.BaseEntity;
import com.ls.lserp.common.persistence.Page;
import com.ls.lserp.common.utils.CollectionsUtils;
import com.ls.lserp.common.utils.ResourcesUtil;
import com.ls.lserp.common.utils.StringUtils;
import com.ls.lserp.common.utils.excel.ExportExcel;
import com.ls.lserp.common.utils.excel.ImportExcel;
import com.ls.lserp.common.web.BaseController;
import com.ls.lserp.modules.common.entity.UploadFile;
import com.ls.lserp.modules.custom.service.CustomService;
import  com.ls.lserp.modules.order.entity.DesignOption;
import groovy.util.ResourceException;
import org.apache.commons.collections.map.HashedMap;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.servlet.support.RequestContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.ConstraintViolationException;
import java.io.IOException;
import java.util.*;

/**
 * 用户Controller
 * @author zhangqian
 * @version 2016-11-10
 */
@Controller
@RequestMapping(value = "${adminPath}/custom/customitem")
public class CustomController extends BaseController {

	@Autowired
	private CustomService customerService;
    @Autowired
    Configuration freemarkerConfiguration;
	
	//子项session
	private final String DESIGNOPTIONSUBLIST="designOptionSubList";
	
	/**
     * 取得主表信息
     * @param id
     * @param request
     * @return
     */
    @ModelAttribute
    public DesignOption get(@RequestParam(required=false) String id) {
        
        if (StringUtils.isNotBlank(id)){
            DesignOption designOption=customerService.getDesignOption(Long.parseLong(id));
            return designOption;
        }else{
            return new DesignOption();
        }
    }

    /**
     * 定制项目列表(初始list列表显示)
     * @param user
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequiresPermissions("custom:customitem:view")
    @RequestMapping(value = {""})
    public String searchList(){
        return "modules/custom/customitem/cusProList";
    }

	/**
     * 定制项目列表(初始list列表显示)
     * @param user
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequiresPermissions("custom:customitem:view")
    @RequestMapping(value = {"searchList"})
    @ResponseBody
    public String searchList(DesignOption designOption, HttpServletRequest request, HttpServletResponse response, Model model,String[] values)throws Exception {
        Map<Object, Object> listMap = new HashMap<Object, Object>();
        // ajax回调时使用的一览list名
        request.setAttribute(Global.LIST_NAME, "designOption");
        // 画面取得的检索项目
        String styleCategoryCD = designOption.getStyleCategoryCD();
        String searchParam = "&styleCategoryCD=" + styleCategoryCD;
        //放到Attribute里，使用Global类里面的SEARCH_PAEAM作为key
        request.setAttribute(Global.SEARCH_PAEAM, searchParam);
        // 查询一览页面数据
        Page<DesignOption> page = customerService.findDesignOption(new Page<DesignOption>(request, response),
                designOption);
        // 读取文件生成字符串
        String strUri = request.getContextPath() + Global.getAdminPath();
        String strHtml = "";
        Map<String, Object> map = new HashedMap();
        map.put("adminUri", strUri);
        map.put("customItemList", page.getList());
        map.put("pageNo", page.getPageNo());
        map.put("pageSize", page.getPageSize());
        map.put("springMacroRequestContext", new RequestContext(request));
        strHtml = FreeMarkerTemplateUtils.processTemplateIntoString(freemarkerConfiguration.getTemplate ("CustomItemList.ftl"),map);
        listMap.put("designOption", strHtml);
        listMap.put("page", page.getHtml());
        // ajax返回结果
        return renderString(response, listMap);
    }
    
    
    /**
     * 根据itemvalue查询父项是否已经存在
     * @param designOption
     * @return
     */
    @ResponseBody
    @RequiresPermissions("custom:customitem:edit")
    @RequestMapping(value = "checkItemValue")
    public String checkItemValue(String oldItemValue, String itemValue) {

        try {
            if (itemValue != null && itemValue.toUpperCase().equals(oldItemValue.toUpperCase())) {
                return "true";
            } else if (itemValue != null&& customerService.searchDesginOptionInfoByItemValue(itemValue) == null&& customerService.searchDesginOptionInfoByItemCD(itemValue) == null) {
                return "true";
            }
            return "false";

        } catch (Exception e) {
            // 记录日志
            logger.error(e.getMessage(), e);
        }

        return "false";

    }
    
    
    /**
     * 根据itemCD查询父项是否已经存在
     * @param designOption
     * @return
     */
    @ResponseBody
    @RequiresPermissions("custom:customitem:edit")
    @RequestMapping(value = "checkItemCd")
    public String checkItemCd(String oldItemCD, String itemCD) {

        try {
            if (itemCD != null && itemCD.toUpperCase().equals(oldItemCD.toUpperCase())) {
                return "true";
            } else if (itemCD != null&& customerService.searchDesginOptionInfoByItemCD(itemCD) == null) {
                return "true";
            }
            return "false";

        } catch (Exception e) {
            // 记录日志
            logger.error(e.getMessage(), e);
        }

        return "false";

    }
    
    
    /**
     * 创建定制项目页面(父项)
     * @param user
     * @param model
     * @return
     */
    @RequiresPermissions("custom:customitem:edit")
    @RequestMapping(value = "form")
    public String form(DesignOption designOption,Model model,HttpSession session) {

            if(designOption.getId()==null){
                // 清空创建的子项
                session.setAttribute(DESIGNOPTIONSUBLIST, new ArrayList<DesignOption>());
                
             // 父项value变子项
                model.addAttribute("design", designOption);
            
            }else{
                // 父项value变子项
                model.addAttribute("design", designOption);
                
                // 获取子项目
                DesignOption designOptionSub = new DesignOption();
                // 父项Code
                designOptionSub.setItemValue(designOption.getItemValue());
                
                // zq test
                List<DesignOption> list= customerService.findSubDesignOption(designOptionSub);
                model.addAttribute("list", list);
                
                session.setAttribute(DESIGNOPTIONSUBLIST, list);
                return "modules/custom/customitem/cusProEdit";
            }
            return "modules/custom/customitem/cusProEdit";
            
    }
    /**
     * 保存项目信息
     * @param Order
     * @param request
     * @param model
     * @param response
     * @return
     */
    @RequiresPermissions("custom:customitem:edit")
    @RequestMapping(value = "saveSub")
    @ResponseBody
    public String saveSub(DesignOption designOption,UploadFile  uploadFile, HttpServletRequest request, Model model, HttpServletResponse response,HttpSession session){
        try {
            // 获取创建的子项
            List<DesignOption> listSubItems = (List<DesignOption>) session.getAttribute(DESIGNOPTIONSUBLIST);
            // 保存图片
            // 图片来源：1.电脑端 ,2.手机端
            uploadFile.setFileSource(1L);
            // 所在模块区分（1:需求单 2:款式 3:订单 4:测试 5:工艺图片）
            uploadFile.setModuleKbn(2L);
            // ftp文件名
            uploadFile.setFtpFile(ResourcesUtil.getConfig("custom_picture_url"));

            // 上传文件路径(以免两个值互相影响)
            String filePath = uploadFile.getFilePath();
            // 前台显示路径
            uploadFile.setShowImgUrl(filePath);
            // 上传文件路径
            uploadFile.setFilePath(uploadFile.getFilePath().substring(0,uploadFile.getFilePath().lastIndexOf('/') + 1));
            // 上传文件
            uploadFile.setUploadFile(filePath.substring(filePath.lastIndexOf('/') + 1));

            designOption.setUploadFile(uploadFile);
            // 加入子项信息

            int delIndex=designOption.getDelIndex();
          
            if(delIndex==-1){
                listSubItems.add(designOption);
            }else{
                //delIndex子项目里面修改的位置
                listSubItems.get(delIndex).setItemValue(designOption.getItemValue());
                listSubItems.get(delIndex).setItemValue(designOption.getItemValue());
                listSubItems.get(delIndex).setItemNameCN(designOption.getItemNameCN());
                listSubItems.get(delIndex).setItemNameEN(designOption.getItemNameEN());
                listSubItems.get(delIndex).setItemNameJP(designOption.getItemNameJP());
                listSubItems.get(delIndex).setEnableFlag(designOption.getEnableFlag());
                listSubItems.get(delIndex).setItemCost(designOption.getItemCost());
                listSubItems.get(delIndex).setVersion(designOption.getVersion());
                if(listSubItems.get(delIndex).getUploadFile() != null){
                	designOption.getUploadFile().setFileId(listSubItems.get(delIndex).getUploadFile().getFileId());
                }
                listSubItems.get(delIndex).setUploadFile(designOption.getUploadFile());
                listSubItems.get(delIndex).setRemarks(designOption.getRemarks());
            }
            session.setAttribute(DESIGNOPTIONSUBLIST, listSubItems);
            return "true";
        
        }catch(Exception e){
            // 记录日志
            logger.error(e.getMessage(), e);
            return "false";
        }
        
    }
    
    
    /**
     * 保存项目信息
     * @param Order
     * @param request
     * @param model
     * @param response
     * @return
     * @throws ResourceException 
     */
    @RequiresPermissions("custom:customitem:edit")
    @RequestMapping(value = "save")
    @ResponseBody
    public String save(DesignOption designOption, HttpServletRequest request, Model model, HttpServletResponse response,HttpSession session) throws ResourceException {
    	if(designOption.getId()!=null){
			   
			//判断数据是否删除
    		DesignOption designOptionNew=get(designOption.getId().toString());
            if(designOptionNew==null || BaseEntity.DEL_FLAG_DELETE.equals(designOption.getDeleteFlag())){
                return renderString(response,AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
            }
			
		    if(designOption.getVersion()==get(designOption.getId().toString()).getVersion()){
		    	designOption.setVersion(designOption.getVersion()+1);
		    }else{
		        return renderString(response,AjaxDone.error(getText("This_record_has_been_deleted_or_modified_the_operation_failed")));
		    }
		}else{
			designOption.setVersion(1L);
		}
    	try {
            // 获取创建的子项
            List<DesignOption> designOptionSubList = (List<DesignOption>) session.getAttribute(DESIGNOPTIONSUBLIST);
            
           // 获取创建子项
            designOption.setDesignOptionSubList(designOptionSubList);
            
            customerService.saveDesignOption(designOption);
            // 清空创建的子项
            session.setAttribute(DESIGNOPTIONSUBLIST, new ArrayList<DesignOption>());
            
            // 保存成功返回提示信息
            return renderString(response,AjaxDone.ok(ResourcesUtil.getFormatProperties("messages", "custom_save_success", new String[]{designOption.getItemCD()})));
    	} catch (Exception e) {
            // 记录日志
            logger.error(e.getMessage(), e);
			 // 提示错误信息
            return renderString(response,AjaxDone.ok(ResourcesUtil.getFormatProperties("messages", "custom_save_success", new String[]{designOption.getItemCD()})));
	     }
    }

    /**
     * 进入编辑定制项目页面(父项)
     * @param user
     * @param model
     * @return
     */
    /**
     * 进入编辑定制项目页面(父项)
     * @param user
     * @param model
     * @return
     */
    @RequiresPermissions("custom:customitem:view")
    @RequestMapping(value = "showParentItem")
    public String showParentItem(DesignOption designOption, HttpServletRequest request, HttpServletResponse response, Model model, HttpSession session) {

        try {

            // 父项value变子项
            model.addAttribute("design", designOption);

            // 获取子项目
            DesignOption designOptionSub = new DesignOption();
            // 父项Code
            designOptionSub.setItemValue(designOption.getItemValue());

            // zq test
            List<DesignOption> list= customerService.findSubDesignOption(designOptionSub);
            model.addAttribute("list", list);

            return "modules/custom/customitem/cusProShow";

        } catch (Exception e) {
            // 记录日志
            logger.error(e.getMessage(), e);
            return "";
        }
    }
    /**
     * 进入编辑定制项目页面--创建子项目
     * @param user
     * @param model
     * @return
     */
    @RequiresPermissions("custom:customitem:edit")
    @RequestMapping(value = "createSubItem")
    public String createSubItem(DesignOption designOption,RedirectAttributes redirectAttributes, Model model,HttpSession session) {

            int delIndex=designOption.getDelIndex();
            String itemCD=designOption.getItemCD();
            if(delIndex!=-1){
                // 获取当前创建的子项
                List<DesignOption> listSubItems = (List<DesignOption>) session.getAttribute(DESIGNOPTIONSUBLIST);
                designOption=listSubItems.get(delIndex);
                designOption.setDelIndex(delIndex);
                designOption.setItemCD(itemCD);
                
            }
            // 将父项itemCD带回页面
            model.addAttribute("design", designOption);
            return "modules/custom/customitem/cusProSubEdit";

    }

    /**
     * 根据父项value,查找相关子项
     * @return
     */
    @RequiresPermissions("custom:customitem:view")
    @RequestMapping(value = "searchSubList")
    public String searchSubList(DesignOption designOption, HttpServletRequest request, HttpServletResponse response, Model model, HttpSession session) {

        try {

            // 获取当前创建的子项
            List<DesignOption> listSubItems = (List<DesignOption>) session.getAttribute(DESIGNOPTIONSUBLIST);
            model.addAttribute("list", listSubItems);
            return "modules/custom/customitem/cusProEdit";

        } catch (Exception e) {
            // 记录日志
            logger.error(e.getMessage(), e);
            return null;
        }
    }


    /**
     * 删除款式父项（逻辑删除）
     * @param DesignOption
     * @return
     */
    @RequiresPermissions("custom:customitem:edit")
    @RequestMapping(value = "deleteDesignOption")
    public String deleteDesignOption(DesignOption DesignOption,HttpServletRequest request, Model model, HttpServletResponse response ) {
        try {
            
            // 删除
            DesignOption.preUpdate();
            DesignOption.setVersion(DesignOption.getVersion()+1);
            customerService.deleteDesignOption(DesignOption);
            // 删除定制项目成功!
            return renderString(response, AjaxDone.ok(getText("custom_delet_success")));
            
        } catch (Exception e) {
            // 记录日志
            logger.error(e.getMessage(), e);
            // System_error_please_contact_your_administrator
            return renderString(response, AjaxDone.error(getText("System_error_please_contact_your_administrator")));
            
        }
        
    }
    
    /**
     * 删除款式子项（逻辑删除）
     * @param DesignOption
     * @return
     */
    @RequiresPermissions("custom:customitem:edit")
    @RequestMapping(value = "deleteSubDesignOption")
    public String deleteSubDesignOption(DesignOption designOption,Model model,HttpSession session ) {

        try {

            // 获取当前创建的子项
            List<DesignOption> listSubItems = (List<DesignOption>) session.getAttribute(DESIGNOPTIONSUBLIST);
            // 删除子项
            listSubItems.get(designOption.getDelIndex()).preUpdate();
            listSubItems.get(designOption.getDelIndex()).setVersion(listSubItems.get(designOption.getDelIndex()).getVersion() +1);
            listSubItems.get(designOption.getDelIndex()).setDeleteFlag("1");

            //listSubItems.remove(designOption.getDelIndex());

            // 在session里重新存入子项
            session.setAttribute(DESIGNOPTIONSUBLIST, listSubItems);
            // 在前台输出子项
            model.addAttribute("list", listSubItems);
            
            return "modules/custom/customitem/cusProEdit";
        } catch (Exception e) {
            // 记录日志
            logger.error(e.getMessage(), e);
            return "modules/custom/customitem/cusProEdit";
        }
        
    }


    /**
     * 下载导入定制项目模板
     * @param response
     * @param redirectAttributes
     * @return
     */
    @RequiresPermissions("custom:customitem:view")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response) {
        try {
            String fileName = getText("custom_importTemplate");
            DesignOption designOption=new DesignOption();
            List<DesignOption> list = customerService.findAllListExport(designOption); 
            
            // custom_msg04 :定制项目
            new ExportExcel(getText("custom_msg04"), DesignOption.class, 2).setDataList(list).write(response, fileName).dispose();
            return null;
        } catch (Exception e) {
            // 记录日志
            logger.error(e.getMessage(), e);
        }
        
        // 提示错误信息
        return renderString(response,AjaxDone.error(getText("System_error_please_contact_your_administrator")));
      
    }
    /**
     * 导入定制项目
     * @param file
     * @param redirectAttributes
     * @return
     * @throws IOException 
     * @throws InvalidFormatException 
     * @throws IllegalAccessException 
     * @throws InstantiationException 
     */
    @RequiresPermissions("custom:customitem:edit")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    @ResponseBody
    public String importFile(MultipartFile file, HttpServletResponse response)throws InvalidFormatException, IOException, InstantiationException,IllegalAccessException {
        Integer successNum = 0;
        Integer failureNum = 0;
        StringBuilder failureMsg = new StringBuilder();
        ImportExcel ei = new ImportExcel(file, 1, 0);
        List<DesignOption> list = ei.getDataList(DesignOption.class);

        // 判断数据值是否重复
        Set set = new HashSet(CollectionsUtils.extractToList(list, "itemValue"));
        if (list.size() != set.size()) {
            failureMsg.append("<br/>" + getText("custom_msg02"));
            return renderString(response, AjaxDone.error(failureMsg.toString()));
        }

        for (DesignOption designOption : list) {
            try {
                if (StringUtils.isBlank(designOption.getItemValue())
                        || StringUtils.isBlank(designOption.getItemNameCN())
                        || StringUtils.isBlank(designOption.getItemNameEN())
                        || StringUtils.isBlank(designOption.getItemNameJP())) {
                    // custom_msg01 :必填项数据存在空值，请检查数据！
                    return renderString(response,
                            AjaxDone.error(getText("custom_msg01")));
                }
            } catch (ConstraintViolationException ex) {
                // 记录日志
                logger.error(ex.getMessage(), ex);
                // custom_msg04 :定制项目 custom_msg05: 导入失败：
                failureMsg.append("<br/>" + getText("custom_msg04")+ designOption.getItemCD() + "-" + designOption.getItemValue()+ getText("custom_msg05"));
                List<String> messageList = BeanValidators.extractPropertyAndMessageAsList(ex, ": ");
                for (String message : messageList) {
                    failureMsg.append(message + "; ");
                    failureNum++;
                }
            } catch (Exception ex) {
                // 记录日志
                logger.error(ex.getMessage(), ex);
                // custom_msg04: 定制项目custom_msg05: 导入失败：
                failureMsg.append("<br/>" + getText("custom_msg04")+ designOption.getItemCD() + "-" + designOption.getItemValue()+ getText("custom_msg05") + ex.getMessage());
            }
        }
        if (failureNum > 0) {
            // custom_msg06:，失败custom_msg07:条定制项目数据，导入信息如下：
            failureMsg.insert(0, getText("custom_msg06") + failureNum+ getText("custom_msg07"));
            return renderString(response,AjaxDone.error(getText("System_error_please_contact_your_administrator")+ failureMsg.toString()));
        } else {
            successNum = customerService.saveCustomImport(list);
            // custom_msg08:已成功导入custom_msg09:条定制项目数据"
            return renderString(response,AjaxDone.ok(getText("custom_msg08") + successNum+ getText("custom_msg09")));
        }
    }

}
